package com.cts.tmall.app.controller;

import com.cts.tmall.com.exception.SystemException;
import com.cts.tmall.com.message.BaseRsp;
import com.cts.tmall.com.message.RspCode;
import com.google.common.collect.ImmutableMap;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 异常统一处理
 *
 * @author leibing.song
 * @since 2020-07-13
 */
@Slf4j
@RestController
@RequestMapping("/api/error")
public class ErrorController {

    @RequestMapping
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public BaseRsp failure(@RequestAttribute Exception exception) {
        log.error("请求处理失败！", exception);
        if (exception != null && exception instanceof BindException) {
            // 处理参数校验失败
            List<Map<String, String>> fieldErrors = new ArrayList<>();
            BindException bindException = (BindException) exception;
            if (CollectionUtils.isNotEmpty(bindException.getFieldErrors())) {
                for (FieldError fieldError : bindException.getFieldErrors()) {
                    fieldErrors.add(ImmutableMap.of(fieldError.getField(), fieldError.getDefaultMessage()));
                }
            }
            return new BaseRsp()
                    .setRspCode(RspCode.FAILURE_PARAMS.getRspCode())
                    .setRspDesc(RspCode.FAILURE_PARAMS.getRspDesc())
                    .setRspData(fieldErrors);
        } else if (exception != null && exception instanceof SystemException) {
            // 处理系统异常，返回指定的错误码
            SystemException systemException = (SystemException) exception;
            return new BaseRsp()
                    .setRspCode(systemException.getRspCode())
                    .setRspDesc(systemException.getRspDesc());
        } else {
            // 其他类型异常，返回通用的错误码
            return new BaseRsp()
                    .setRspCode(RspCode.FAILURE_SYSTEM.getRspCode())
                    .setRspDesc(RspCode.FAILURE_SYSTEM.getRspDesc());
        }
    }
}
